package com.hongyi.service.Impl;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.gson.Gson;
import com.hongyi.pojo.PostRequest;
import com.hongyi.utils.http.HttpUtils;
import okhttp3.OkHttpClient;
import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestClientException;
import org.springframework.web.client.RestTemplate;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * @Author: hongyi
 * @CreateTime: 2024-10-21
 */


@Service
public class ApiServiceImpl implements ApiService {
    //  private final OkHttpClient client = new OkHttpClient();
    private final RestTemplate restTemplate = new RestTemplate();
    private final ObjectMapper objectMapper = new ObjectMapper();

   /* @Override
    public PostRequest createPost(PostRequest postRequest) {
        String url = "https://jsonplaceholder.typicode.com/posts"; // 第三方api地址
        return restTemplate.postForEntity(url, postRequest, PostRequest.class).getBody();
    }*/

    @Override
    public void createPost(PostRequest postRequest) {
        String host = "https://jsonplaceholder.typicode.com";
        String path = "/posts";
        String url = host + path; // 组装完整的 URL
        String method = "POST";

        // 设置请求头
        Map<String, String> headers = new HashMap<>();
        headers.put("Content-Type", "application/json");

        // 不需要查询参数
        Map<String, String> querys = new HashMap<>();

        try {
            // 将 postRequest 转换为 JSON 字符串
            // String requestBody = objectMapper.writeValueAsString(postRequest); // 将 postRequest 转换为 JSON 字符串 请求数据 对象转化为JSONg格式的

            Gson gson = new Gson();
            String requestBody = gson.toJson(postRequest);


            // 执行 POST 请求
            HttpResponse response = HttpUtils.doPost(host, path, method, headers, querys, requestBody);

            // 检查响应状态码
            if (response.getStatusLine().getStatusCode() != 201) {
                throw new RuntimeException("请求失败，状态码：" + response.getStatusLine().getStatusCode());
            }

            // 处理响应体（可选）
            String jsonResponse = EntityUtils.toString(response.getEntity());
            // 如果需要，你可以在这里进一步处理 jsonResponse，例如转换为对象

        } catch (JsonProcessingException e) {
            throw new RuntimeException("请求数据转换失败: " + e.getMessage(), e);
        } catch (RestClientException e) {
            throw new RuntimeException("请求失败: " + e.getMessage(), e);
        } catch (IOException e) {
            throw new RuntimeException("输入输出错误: " + e.getMessage(), e);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

}
